﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lambda表达式改写代理程序
{
    class Program
    {
        public delegate bool NumberPredicate(int nums);//设为static无效

        static void Main(string[] args)
        {
            int[] nums = { 1, 3, 5, 3, 4, 6, 7, 8, 9 };
            NumberPredicate evenPredicate = number => (number % 2 == 0);

            Console.WriteLine("Use a lambda expression variable:{0}\n", evenPredicate(4));
            
            //Lambda 语句中的 => 符号读作 "go to"  =>之前为函数的参数，之后为语句块，有时候只是个表达式，
            //没有指定返回值，编译器会从返回值推断出返回类型
            List<int> evenNumbers = FilterNumbers(nums, number => number % 2 == 0);//表达式Lambda(Expression Lambda)
            DisplayList("use a lambda expression to filter even numbers:", evenNumbers);

            List<int> oddNumbers = FilterNumbers(nums, (int number) => number % 2 == 1); //表达式Lambda(Expression Lambda)
            DisplayList("use a lambda expression to filter odd numbers:", oddNumbers);

            List<int> isOver5 = FilterNumbers(nums, (int number) => { return number > 5; });//语句Lambda(Statement Lambda)
            DisplayList("use a lambda statement to filter numbers greater than 5:", isOver5);
            Console.ReadKey();
        }

        private static List<int> FilterNumbers(int[] nums, NumberPredicate predicate)
        {
            List<int> results = new List<int>();

            foreach (int item in nums)
            {
                if (predicate(item))
                {
                    results.Add(item);
                }
            }//end for

            return results;
        }//end method FilterNumbers

        private static void DisplayList(string header, List<int> results)
        {
            Console.Write(header);

            foreach (int item in results)
            {
                Console.Write("  {0}", item);
            }//end for

            Console.WriteLine("\n");
        }//end method DisplayList
    }
}
